//
//  WNFuncManager.swift
//  WalkNovel
//
//  Created by Kevin on 2023/7/4.
//

import UIKit

/// 转成Int
func wn_toInt(_ v : Any?) -> Int {
    guard let v = v else {
        return 0
    }
    if let num = v as? NSNumber {
        return num.intValue
    }else if let str = v as? String {
        return Int(str) ?? 0
    }else {
        return 0
    }
}
/// 转成Float
func wn_toFloat(_ v : Any?) -> Float {
    guard let v = v else {
        return 0
    }
    if let num = v as? NSNumber {
        return num.floatValue
    }else if let str = v as? String {
        return Float(str) ?? 0
    }else {
        return 0
    }
}

func wn_toCGFloat(_ v : Any?) -> CGFloat {
    guard let v = v else {
        return 0.0
    }
    if let num = v as? NSNumber {
        return CGFloat(num.floatValue)
    }else if let str = v as? String {
        return CGFloat(Float(str) ?? 0.0)
    }else {
        return 0.0
    }
}

/// 转成String
func wn_toString(_ v : Any?) -> String {
    guard let v = v else { return "" }
    if v is String {
        return v as! String
    }else if let num = v as? NSNumber {
        return num.stringValue
    }
    return ""
}

/// 判断字符串 || 数字 是否为空或者nil
func isBlank(_ v : Any?) -> Bool {
    guard let v = v else { return true }
    let tempString = wn_toString(v).trimmingCharacters(in: .whitespacesAndNewlines)
    return tempString.isEmpty
}

func WNLog<T> (_ message: T,
              file: String = #file,
              method: String = #function,
              line: Int = #line) {
    #if DEBUG
        print("\((file as NSString).lastPathComponent)[\(line)],\(method):\(message)")
    #endif
}

// MARK: - 查找顶层控制器
/// 获取顶层控制器 根据window
func wn_getTopVC() -> (UIViewController?) {
    // UIApplication.shared.keyWindow
    var window = appDelegate.wn_window
    if window?.windowLevel != UIWindow.Level.normal {
        let windows = UIApplication.shared.windows
        for  windowTemp in windows {
            if windowTemp.windowLevel == UIWindow.Level.normal {
                window = windowTemp
                break
            }
        }
    }
    let vc = window?.rootViewController
    return wn_getTopVC(withCurrentVC: vc)
}

/// 根据控制器获取 顶层控制器
func wn_getTopVC(withCurrentVC VC :UIViewController?) -> UIViewController? {
    if VC == nil {
        return nil
    }
    if let presentVC = VC?.presentedViewController {
        //modal出来的 控制器
        return wn_getTopVC(withCurrentVC: presentVC)
    }else if let tabVC = VC as? UITabBarController {
        // tabBar 的跟控制器
        if let selectVC = tabVC.selectedViewController {
            return wn_getTopVC(withCurrentVC: selectVC)
        }
        return nil
    }else if let naiVC = VC as? UINavigationController {
        // 控制器是 nav
        return wn_getTopVC(withCurrentVC:naiVC.visibleViewController)
    }else {
        // 返回顶控制器
        return VC
    }
}

func wn_getTextH(textStr: String, font: UIFont, width: CGFloat, lineSpace: CGFloat = 1.2, kernSpace: CGFloat = 0) -> CGFloat {
    let size = CGSize(width: width, height: CGFloat(MAXFLOAT))
    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.lineSpacing = lineSpace
    paragraphStyle.lineBreakMode = .byWordWrapping
    let attributes = [NSAttributedString.Key.font: font, NSAttributedString.Key.paragraphStyle: paragraphStyle.copy(), NSAttributedString.Key.kern: kernSpace]
    let text = textStr as NSString
    let rect = text.boundingRect(with: size, options:[.usesLineFragmentOrigin, .usesFontLeading], attributes: attributes, context:nil)
    return rect.size.height
}

/// 计算文字宽度
func wn_getTextW(textStr: String, font: UIFont, height: CGFloat) -> CGFloat {
    let normalText: NSString = textStr as NSString
    let size = CGSize.init(width: CGFloat(MAXFLOAT), height: height)
    let dic = NSDictionary(object: font, forKey: kCTFontAttributeName as! NSCopying)
    let stringSize = normalText.boundingRect(with: size, options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: dic as? [NSAttributedString.Key : AnyObject], context:nil).size
    return stringSize.width
}

func getTextRectSize(_ text: NSString, font: UIFont,size: CGSize) -> CGRect {
     let attributes = [NSAttributedString.Key.font: font]
     let option = NSStringDrawingOptions.usesLineFragmentOrigin
     let rect:CGRect = text.boundingRect(with: size, options: option,
                  attributes: attributes, context: nil)
     return rect
 }

/// 处理各种跳转
func handleTypeStr(_ str: String, _ needPop: Bool = true) {
    guard !isBlank(str) else {
        return
    }
    let queryArr = str.components(separatedBy: "&")
    var dic = [String: String]()
    for i in queryArr {
        let arr = i.components(separatedBy: "=")
        dic[arr[0]] = arr[1]
    }
    let bookId = dic["bookId"] ?? ""
    let chapterId = dic["chapterId"] ?? ""
    if bookId.count > 0 {
        if needPop {
            // TODO: - ⚠️：深度链接跳转，开屏展示视图不展示
            saveIsDeeplink(true)
            hidenLibRec()
            wn_getTopVC()?.navigationController?.popToRootViewController(animated: false)
            wn_getTopVC()?.tabBarController?.tabBar.isHidden = false
            WNThread.wn_delay(0.25) {
                wn_getTopVC()?.tabBarController?.selectedIndex = 1
                wn_getTopVC()?.wn_pushBookVC(bookId, chapterId)
            }
        }
    }
}
